#include "settingsmanager.h"
#include "config.h"
#include "logger.h"
#include "../io/serialportmanager.h"
#include "../core/devicemanager.h"
#include <QThread>

SettingsManager::SettingsManager(Config *config,
                                 SerialPortManager *portManager,
                                 DeviceManager *deviceManager,
                                 QObject *parent)
    : QObject(parent), m_config(config), m_portManager(portManager), m_deviceManager(deviceManager), m_isPolling(false)
{
    // 连接设备管理器信号
    connect(m_deviceManager, &DeviceManager::topologyDiscoveryCompleted,
            this, &SettingsManager::onTopologyDiscoveryCompleted);
    connect(m_deviceManager, &DeviceManager::topologyDiscoveryProgress,
            this, &SettingsManager::onTopologyDiscoveryProgress);
    connect(m_deviceManager, &DeviceManager::scanningChanged,
            this, &SettingsManager::isScanningChanged);

    Logger::instance()->log(LogLevel::Info, "SettingsManager: 设置管理器已初始化");
}

SettingsManager::~SettingsManager()
{
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 设置管理器已销毁");
}

// 加载当前配置
QVariantMap SettingsManager::loadCurrentConfig()
{
    QVariantMap config;

    config["bus1Port"] = m_config->getSerialPort1();
    config["bus2Port"] = m_config->getSerialPort2();
    config["bus3Port"] = m_config->getSerialPort3();
    config["baudRate"] = m_config->getBaudRate();

    config["bus1Opened"] = m_portManager->isPortOpen(m_config->getSerialPort1());
    config["bus2Opened"] = m_portManager->isPortOpen(m_config->getSerialPort2());
    config["bus3Opened"] = m_portManager->isPortOpen(m_config->getSerialPort3());

    return config;
}

// 验证配置
QString SettingsManager::validateConfiguration(const QString &bus1Port,
                                               const QString &bus2Port,
                                               const QString &bus3Port)
{
    // 检查是否为空
    if (bus1Port.isEmpty() || bus2Port.isEmpty() || bus3Port.isEmpty())
    {
        return "串口配置不能为空";
    }

    // 检查是否重复
    if (bus1Port == bus2Port || bus1Port == bus3Port || bus2Port == bus3Port)
    {
        return "串口配置不能重复";
    }

    return QString(); // 返回空字符串表示验证通过
}

// 应用配置
bool SettingsManager::applyConfiguration(const QString &bus1Port,
                                         const QString &bus2Port,
                                         const QString &bus3Port,
                                         int baudRate)
{
    // 验证配置
    QString validationError = validateConfiguration(bus1Port, bus2Port, bus3Port);
    if (!validationError.isEmpty())
    {
        emit configurationFailed(validationError);
        Logger::instance()->log(LogLevel::Error,
                                QString("SettingsManager: 配置验证失败 - %1").arg(validationError));
        return false;
    }

    // 先停止系统
    stopSystem();

    // 保存配置
    m_config->setSerialPort1(bus1Port);
    m_config->setSerialPort2(bus2Port);
    m_config->setSerialPort3(bus3Port);
    m_config->setBaudRate(baudRate);
    m_config->save();

    Logger::instance()->log(LogLevel::Info,
                            QString("SettingsManager: 配置已保存 - Bus1:%1, Bus2:%2, Bus3:%3, 波特率:%4")
                                .arg(bus1Port)
                                .arg(bus2Port)
                                .arg(bus3Port)
                                .arg(baudRate));

    // 清空旧的总线配置
    m_deviceManager->clearBusConfigs();

    // 添加新的总线配置
    m_deviceManager->addBusConfigQml(1, "配电室A", bus1Port, 1, 40);
    m_deviceManager->addBusConfigQml(2, "配电室B", bus2Port, 41, 80);
    m_deviceManager->addBusConfigQml(3, "配电室C", bus3Port, 81, 120);

    emit configurationApplied();
    emit systemStatusChanged("配置已更新，请启动系统");

    return true;
}

// 启动系统
bool SettingsManager::startSystem()
{
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 启动系统");

    // 如果已经在运行，先停止
    if (m_isPolling)
    {
        Logger::instance()->log(LogLevel::Warning, "SettingsManager: 系统已在运行，先停止");
        stopSystem();
        QThread::msleep(500); // 等待完全停止
    }

    // 检查总线配置
    if (m_deviceManager->busConfigCount() == 0)
    {
        emit configurationFailed("未配置总线，请先应用配置");
        return false;
    }

    emit systemStatusChanged("正在打开串口...");

    // 打开所有串口
    QString bus1Port = m_config->getSerialPort1();
    QString bus2Port = m_config->getSerialPort2();
    QString bus3Port = m_config->getSerialPort3();
    int baudRate = m_config->getBaudRate();

    bool success1 = m_portManager->openPort(bus1Port, baudRate);
    bool success2 = m_portManager->openPort(bus2Port, baudRate);
    bool success3 = m_portManager->openPort(bus3Port, baudRate);

    if (!success1 || !success2 || !success3)
    {
        QString errorMsg = QString("串口打开失败: %1=%2, %3=%4, %5=%6")
                               .arg(bus1Port)
                               .arg(success1 ? "成功" : "失败")
                               .arg(bus2Port)
                               .arg(success2 ? "成功" : "失败")
                               .arg(bus3Port)
                               .arg(success3 ? "成功" : "失败");

        Logger::instance()->log(LogLevel::Error, errorMsg);

        // 回滚：关闭已打开的串口
        if (success1)
        {
            m_portManager->closePort(bus1Port);
        }
        if (success2)
        {
            m_portManager->closePort(bus2Port);
        }
        if (success3)
        {
            m_portManager->closePort(bus3Port);
        }

        emit configurationFailed(errorMsg);
        emit systemStatusChanged("串口打开失败");
        return false;
    }

    emit systemStatusChanged("串口已打开，开始拓扑识别...");

    // 启动拓扑识别
    m_deviceManager->startTopologyDiscovery(500);

    return true;
}

// 停止系统
void SettingsManager::stopSystem()
{
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 停止系统");

    // 停止轮询
    m_deviceManager->stopPolling();
    m_isPolling = false;
    emit isPollingChanged();

    // 停止在线监测
    m_deviceManager->stopOnlineMonitor();

    // 停止拓扑识别
    m_deviceManager->stopTopologyDiscovery();

    // 将所有电表设置为离线状态（重要：清理状态）
    m_deviceManager->setAllMetersOffline();

    // 关闭所有串口
    m_portManager->closeAllPorts();

    emit systemStatusChanged("系统已停止");
}

// 重启系统
bool SettingsManager::restartSystem()
{
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 重启系统");

    // 停止系统
    stopSystem();

    // 等待所有组件完全停止（增加等待时间确保线程完全退出）
    // 500ms用于线程停止，500ms用于资源释放
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 等待系统完全停止...");
    QThread::msleep(1000);

    // 启动系统
    Logger::instance()->log(LogLevel::Info, "SettingsManager: 开始重新启动系统");
    return startSystem();
}

// 获取系统状态
QString SettingsManager::getSystemStatus()
{
    if (m_deviceManager->isScanning())
    {
        return "正在扫描设备...";
    }

    if (m_isPolling)
    {
        return QString("系统运行中 - 在线: %1/%2")
            .arg(m_deviceManager->onlineCount())
            .arg(m_deviceManager->totalCount());
    }

    int openedPorts = m_portManager->openedPortCount();
    if (openedPorts > 0)
    {
        return QString("串口已打开 (%1/3)，等待启动").arg(openedPorts);
    }

    return "系统已停止";
}

// 是否正在扫描
bool SettingsManager::isScanning() const
{
    return m_deviceManager->isScanning();
}

// 处理拓扑识别完成
void SettingsManager::onTopologyDiscoveryCompleted(int totalFound)
{
    Logger::instance()->log(LogLevel::Info,
                            QString("SettingsManager: 拓扑识别完成，发现 %1 块在线电表").arg(totalFound));

    emit systemStatusChanged(QString("拓扑识别完成，发现 %1 块在线电表").arg(totalFound));

    // 启动轮询
    bool pollingStarted = m_deviceManager->startPolling(500);
    if (pollingStarted)
    {
        m_isPolling = true;
        emit isPollingChanged();

        // 启动在线监测
        m_deviceManager->startOnlineMonitor(5000, 10);

        emit systemStatusChanged("系统运行中");
    }
    else
    {
        Logger::instance()->log(LogLevel::Error, "SettingsManager: 轮询启动失败");
        emit systemStatusChanged("轮询启动失败");
    }
}

// 处理拓扑识别进度
void SettingsManager::onTopologyDiscoveryProgress(int current, int total)
{
    emit systemStatusChanged(QString("正在扫描设备 %1/%2").arg(current).arg(total));
}
